/* eslint-disable @typescript-eslint/no-var-requires */
import { is } from '@electron-toolkit/utils'
import { app } from 'electron'
import { join } from 'path'
import { createLogger, format, transports } from 'winston'
// import * as DailyRotateFile from 'winston-daily-rotate-file'
const DailyRotateFile = require('winston-daily-rotate-file')
const { combine, timestamp, printf } = format
const isProd = process.env.NODE_ENV !== 'development'
const appName = app.getName()
const logPath = is.dev
  ? join(process.cwd(), 'stores', 'logs')
  : join(app.getPath('appData'), appName, 'stores', 'logs')

// 定义日志格式
const logFormat = printf(({ level, message, timestamp }) => {
  return `${timestamp} [${level.toUpperCase()}]: ${message}`
})

// 创建日志记录器
const logger = createLogger({
  format: combine(timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), logFormat),
  transports: [
    // info 日志文件（按天轮转）
    new DailyRotateFile({
      level: 'info',
      filename: `${logPath}/info-%DATE%.log`,
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '14d'
    }),
    // warn 日志文件（按天轮转）
    new DailyRotateFile({
      level: 'warn',
      filename: `${logPath}/warn-%DATE%.log`,
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '14d'
    }),
    // error 日志文件（按天轮转）
    new DailyRotateFile({
      level: 'error',
      filename: `${logPath}/error-%DATE%.log`,
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '14d'
    }),
    // 控制台输出
    new transports.Console({
      level: 'info',
      // format: format.combine(format.colorize(), format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }))
      format: format.combine(
        format.colorize(),
        format.timestamp({
          format: 'YYYY-MM-DD HH:mm:ss.SSSSSS'
        }),
        format.printf(
          (info) =>
            `${info.timestamp} ${info.level}: ${info.message}` +
            (info.splat !== undefined ? `${info.splat}` : ' ')
        )
      )
    })
  ]
})

// 测试日志输出
// logger.info('This is an info message')
// logger.warn('This is a warning message')
// logger.error('This is an error message')
logger.info(logPath)
logger.info(logPath)
logger.info(logPath)
logger.info(logPath)

export default logger
